<template>
  <div class='container'>
    <el-card>
      <span>{{ $route.query.id ? '试题修改' : '试题录入'}}</span>
      <el-divider></el-divider>

      <div>
        <el-form ref="refForm" :rules="rules" :model="form" label-width="100px" label-position="right">
        <!-- 学科 -->
         <el-form-item label="学科:" prop="subjectID">
          <el-select @change="subChange" v-model="form.subjectID" placeholder="请选择" style="width:400px">
            <el-option
            v-for="item in subjectList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
            </el-option>
          </el-select>
         </el-form-item>

           <!-- 目录 -->
         <el-form-item label="目录:" prop="catalogID">
          <el-select v-model="directoryName" placeholder="请选择" @change="directoryNameChange" style="width:400px">
            <el-option
            v-for="item in catalogList" :key="item.id"
            :label="item.directoryName"
            :value="item.id"></el-option>
          </el-select>
         </el-form-item>

           <!-- 企业 -->
         <el-form-item label="企业:" prop="enterpriseID">
          <el-select v-model="form.enterpriseID" placeholder="请选择" style="width:400px">
            <el-option
            v-for="item in enterpriseList"
            :key="item.id"
            :label="item.company"
            :value="item.id">
            </el-option>
          </el-select>
         </el-form-item>

           <!-- 城市 -->
         <el-form-item label="城市:" required>
         <el-row :gutter="6" type="flex">
          <el-col :span="4">
          <el-form-item prop="province">
           <el-select
           style="width:197px"
          v-model="form.province"
          @change="pvcChange"
          placeholder="请选择">
            <el-option
            v-for="(item,index) in provinceList"
            :key="index"
            :label="item"
            :value="item">
            </el-option>
          </el-select>
         </el-form-item>
         </el-col>
          <!-- 区县 -->
         <el-col>
          <el-form-item prop="city">
           <el-select v-model="form.city" placeholder="请选择" style="width:197px">
            <el-option
            v-for="(item,index) in cityList"
            :key="index"
            :label="item"
            :value="item"></el-option>
          </el-select>
         </el-form-item>
         </el-col>
         </el-row>
         </el-form-item>

           <!-- 方向 -->
         <el-form-item label="方向:" prop="direction">
          <el-select v-model="form.direction" placeholder="请选择" style="width:400px">
            <el-option
            v-for="(item,index) in directionList"
            :key="index"
            :label="item"
            :value="item"></el-option>
          </el-select>
         </el-form-item>

         <!-- 题型 -->
         <el-form-item label="题型:" prop="questionType">
          <el-radio-group v-model="questionTypeId" @change="opsChange">
            <el-radio
            v-for="item in questionType" :key="item.value" :label="item.label"></el-radio>
          </el-radio-group>
         </el-form-item>

         <!-- 难度 -->
         <el-form-item label="难度:" prop="difficulty">
          <el-radio-group v-model="difficultyId" @change="difficultyChange">
            <el-radio
             v-for="item in difficulty" :key="item.value" :label="item.label"></el-radio>
          </el-radio-group>
         </el-form-item>

          <!-- 题干 -->
         <el-form-item label="文章内容" prop="question">
          <quill-editor v-model="form.question"/>
         </el-form-item>

          <!-- 选项 -->
         <el-form-item label="选项:" v-show="isOptions">
          <!-- 单选 -->
          <el-radio-group v-model="radio" @change="radioChange" v-show="isClose">
            <el-radio
            class="options"
            v-for="(item,index) in form.options"
            :key="index"
            :label="item.code">
             <el-row :gutter="10" type="flex" align="middle">
            <el-col :span="2"><p>{{item.code}}: </p></el-col>
            <el-col :span="14"><el-input v-model="item.title"></el-input></el-col>
            <el-col :span="2"><upload/></el-col>
            </el-row>
            </el-radio>
          </el-radio-group>
          <!-- 多选 -->
            <el-checkbox-group v-model="checkList" v-show="!isClose" @change="checkChange">
            <el-checkbox
            class="options"
            v-for="(item,index) in form.options"
            :key="index"
            :label="item.code">
             <el-row :gutter="10" type="flex" align="middle">
            <el-col :span="2"><p>{{item.code}}: </p></el-col>
            <el-col :span="14"><el-input v-model="item.title"></el-input></el-col>
            <el-col :span="2"><upload/></el-col>
            </el-row>
            </el-checkbox>
          </el-checkbox-group>
         </el-form-item>

         <!-- 禁用按钮 -->
         <el-form-item>
          <el-button type="danger" :disabled="isClose" @click="Add">+增加选项与答案</el-button>
         </el-form-item>

         <!-- 解析视频 -->
         <el-form-item label="解析视频:">
          <el-input style="width:400px" v-model="form.videoURL"></el-input>
         </el-form-item>

         <!-- 答案解析 -->
         <el-form-item label="答案解析" prop="answer">
          <quill-editor v-model="form.answer"/>
         </el-form-item>

         <!-- 题目备注 -->
         <el-form-item label="题目备注:">
          <el-input v-model="form.remarks" type="textarea" size="medium" style="width:400px"></el-input>
         </el-form-item>

         <!-- 试题标签 -->
         <el-form-item label="试题标签">
              <el-select
              @change="tagChange"
              v-model="tags"
              multiple
              filterable
             allow-create
             default-first-option
             placeholder="请选择试题标签"
             style="width:400px">
             <el-option
               v-for="item in tagOptions"
               :key="item.id"
               :label="item.tagName"
               :value="item.tagName">
             </el-option>
             </el-select>
         </el-form-item>

         <!-- 确认按钮 -->
         <el-form-item>
          <el-button type="primary" @click="addQuestion">{{ $route.query.id ? '确认修改' : '确认提交'}}</el-button>
         </el-form-item>
      </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import { simple } from '@/api/hmmm/subjects.js'
import { list as directoryList } from '@/api/hmmm/directorys.js'
import { list as enterpriseList } from '@/api/hmmm/companys.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { direction, questionType, difficulty } from '@/api/hmmm/constants.js'
import { list as tagList } from '@/api/hmmm/tags.js'
import { add, detail, update } from '@/api/hmmm/questions.js'
import upload from '../components/upload.vue'
let i = 4
export default {
  components: { upload },
  data () {
    return {
      radio: '',
      checkList: [],
      subjectList: [],
      catalogList: [],
      enterpriseList: [],
      provinceList: [],
      cityList: [],
      directionList: direction,
      questionType: questionType,
      questionTypeId: '单选',
      difficultyId: '简单',
      difficulty: difficulty,
      isClose: true,
      isOptions: true,
      directoryName: '',
      form: {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        questionType: '1',
        difficulty: '1',
        question: '',
        options: [
          {
            title: '',
            code: 'A',
            isRight: 'fales'
          },
          {
            title: '',
            code: 'B',
            isRight: 'fales'
          },
          {
            title: '',
            code: 'C',
            isRight: 'fales'
          },
          {
            title: '',
            code: 'D',
            isRight: 'fales'
          }
        ],
        videoURL: '',
        answer: '',
        remarks: '',
        tags: ''
      },
      tagOptions: [],
      tags: [],
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        directoryName: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        province: [
          { required: true, message: '请选择城市', trigger: 'change' }
        ],
        city: [
          { required: true, message: '请选择区县', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请输入答案解析', trigger: 'blur' }
        ]
      }
    }
  },

  created () {
    this.getSubjectList()
    this.getEnterpriseList()
    this.getProvinceList()
    // 调用请求题目详情函数
    this.loaddetail()
  },

  methods: {
    // 封装题目详情请求函数并回填
    async loaddetail () {
      if (this.$route.query.id) {
        try {
          const { data: res } = await detail(this.$store.state.app.data)
          console.log('题目详情', res)
          this.form = res
          // 格式化处理试题标签
          // 先把响应的试题标签转换为数组格式再回填
          this.form.tags = res.tags
          this.tags = res.tags.split(',')
          // 格式化处理二级目录
          this.directoryName = res.directoryName
          // 判断当前题目题型
          if (res.questionType === '1') {
            this.questionTypeId = '单选'
            this.isClose = true
            // 判断当前题目的正确答案
            res.options.forEach(item => {
              if (item.isRight === 1) {
                this.radio = item.code
              }
            })
          } else if (res.questionType === '2') {
            this.questionTypeId = '多选'
            this.isClose = false
            // 判断当前题目的正确答案
            res.options.forEach(item => {
              if (item.isRight === 1) {
                this.checkList.push(item.code)
              }
            })
          } else {
            this.questionTypeId = '简答'
          }
          // 判断当前题目难度
          if (res.difficulty === '1') {
            this.difficultyId = '简单'
          } else if (res.difficulty === '2') {
            this.difficultyId = '一般'
          } else {
            this.difficultyId = '困难'
          }
        } catch (err) {
          this.$message.error('题目详情请求失败')
        }
      }
    },
    // 获取学科列表
    async getSubjectList () {
      try {
        const res = await simple()
        this.subjectList = res.data
      // console.log(res)
      } catch (err) {
        console.log(err)
      }
    },
    // 学科change事件
    async subChange (id) {
      this.tags = []
      this.directoryName = ''
      if (this.form.subjectID === '') {
        this.catalogList = []
        this.tagOptions = []
      } else {
        // 获取目录列表
        try {
          const res = await directoryList()
          // console.log(res)
          this.catalogList = res.data.items.filter(item => item.subjectID === id)

        // this.form.catalogID =
        } catch (err) {
          console.log(err)
        }

        // 获取标签列表
        try {
          const res = await tagList()
          // console.log(res)
          this.tagOptions = res.data.items.filter(item => item.subjectID === id)
        } catch (err) {
          console.log(err)
        }
      }
      // 获取标签列表
    },
    // 目录选项发生变化事件
    directoryNameChange () {
      console.log(this.catalogList)
      this.catalogList.forEach(item => {
        if (item.id == this.directoryName) {
          console.log('11111')
          this.form.catalogID = item.id
        }
      })
    },
    // 获取企业列表
    async getEnterpriseList () {
      try {
        const res = await enterpriseList()
        // console.log(res)
        this.enterpriseList = res.data.items
      } catch (err) {
        console.log(err)
      }
    },
    // 获取城市列表
    getProvinceList () {
      this.provinceList = provinces()
    },
    // 获取区县列表
    getCityList (province) {
      this.cityList = citys(province)
      // console.log(this.cityList)
    },
    // 省份变化事件
    pvcChange () {
      this.form.city = ''
      if (this.form.province === '') {
        this.cityList = []
      } else {
        this.getCityList(this.form.province)
      }
    },
    // 单选选项变化事件
    radioChange (value) {
      // console.log(value)
      this.form.options.forEach(item => {
        if (item.code === value) {
          item.isRight = true
        } else {
          item.isRight = false
        }
      })
      // console.log(this.form.options)
    },
    // 题型点击事件
    opsChange (label) {
      if (label === '多选') {
        this.isClose = false
        this.isOptions = true
      } else if (label === '单选') {
        this.isClose = true
        this.isOptions = true
      } else if (label === '简答') {
        this.isOptions = false
      }
      this.questionType.forEach(item => {
        if (item.label === label) {
          this.form.questionType = '' + item.value
        }
      })
    },
    // 难度点击事件
    difficultyChange (label) {
      this.difficulty.forEach(item => {
        if (item.label === label) {
          this.form.difficulty = '' + item.value
        }
      })
    },
    // 多选题型点击事件
    checkChange (list) {
      this.form.options.forEach(item => {
        item.isRight = false
      })
      list.forEach(item => {
        this.form.options.forEach(check => {
          if (item === check.code) {
            check.isRight = true
          }
        })
      })
    },
    // 添加选项按钮
    Add () {
      const arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
      // console.log(i)
      if (i < 26) {
        this.form.options.push(
          {
            title: '',
            code: arr[i++],
            isRight: 'fales'
          })
      } else {
        this.$message.error('不能再添加了')
      }
    },
    // 标签change事件
    tagChange () {
    // console.log(this.tags)
    // console.log(...this.tags)
    // let a = this.tags.toString()
    // console.log(a)
      this.form.tags = this.tags.join()
    // console.log(this.form.tags)
    // console.log(b)
    },
    // 确认提交按钮事件
    addQuestion () {
      this.$refs.refForm.validate(valid => {
        if (valid) {
          if (this.$route.query.id) {
            this.update()
          } else {
            this.getAddQuestion()
            // console.log(this.form)
            // console.log( this.$router)
          }
        }
      })
    },
    // 修改题目信息
    async update () {
      try {
        const res = await update(this.form)
        console.log(res)
        // 跳转页面
        this.$router.push('/questions/list')
      } catch (err) {
        this.$message.error(err.message)
      }
    },
    // 提交接口
    async getAddQuestion () {
      try {
        await add(this.form)
        this.$message.success('添加成功')
        this.$refs.refForm.resetFields()
        this.$router.push('/questions/list')
      } catch (err) {
        console.log(err)
      }
    }

  }
}
</script>

<style scoped lang='scss'>
.options {
    display: flex;
    align-items: center;
  margin-top: 20px;
  // .iptcen {
  //   display: flex;
  //   align-items: center;
  // }
}

</style>
